﻿using AutoMapper;
using MediatR;
using RearLivestock.Beginning.Api.Application.Command.ChangeHouse;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.Condition
{
    public class AddConditionHandler : IRequestHandler<AddConditionCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 品相测定仓储
        /// </summary>
        private readonly IBaseRepository<Conditions> conditionsRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<AddChangeHouseHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="conditionsRepository"></param>
        public AddConditionHandler(IMapper mapper, IBaseRepository<Conditions> conditionsRepository, ILogger<AddChangeHouseHandler> logger)
        {
            this.mapper = mapper;
            this.conditionsRepository = conditionsRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(AddConditionCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                Conditions conditions = mapper.Map<Conditions>(request);
                var res = await conditionsRepository.Add(conditions);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                }
                result.Msg = "品相测定成功";
            }
            catch (Exception)
            {
                logger.LogError("品相测定异常");
                result.Msg = "品相测定异常";
            }
            return result;
        }
    }
}
